﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace JESAI.Common.Util
{
    /// <summary>
    /// 图片操作类
    /// </summary>
    public class ImageUtility
    {
        #region 压缩图片
        /// <summary>
        /// 将http连接对应的图片生成到本地并压缩图片
        /// </summary>
        /// <param name="http">http连接对应图片</param>
        /// <param name="newFileName">生成到本地的压缩图片</param>
        public static void CompressImageToLocalFromHttp(string http, string newFileName)
        {
            var ms = GetResponseStream(http);

            Image img = System.Drawing.Image.FromStream(ms);

            CompressImage(img, newFileName);
        }

        /// <summary>
        /// 将本地的图片压缩后并保存到本地
        /// </summary>
        /// <param name="oldFileName">被压缩的图片</param>
        /// <param name="newFileName">压缩后的图片</param>
        public static void CompressImageToLocalFromUrl(string oldFileName, string newFileName)
        {
            Image img = System.Drawing.Image.FromFile(oldFileName);

            CompressImage(img, newFileName);
        }

        /// <summary>
        /// 返回压缩后的字节流
        /// </summary>
        /// <param name="http">http连接对应图片</param>
        /// <returns>返回压缩后的字节流</returns>
        public static byte[] GetCompressStreamFromHttp(string http)
        {
            var ms = GetResponseStream(http);

            Image img = System.Drawing.Image.FromStream(ms);

            return CompressStream(img);
        }

        /// <summary>
        /// 返回压缩后的字节流
        /// </summary>
        /// <param name="oldFileName">被压缩的图片</param>
        /// <returns>返回压缩后的字节流</returns>
        public static byte[] GetCompressStreamFromUrl(string oldFileName)
        {
            Image img = System.Drawing.Image.FromFile(oldFileName);

            return CompressStream(img);
        }

        /// <summary>
        /// 获取http连接对应图片的响应流
        /// </summary>
        /// <param name="http">http连接对应图片</param>
        /// <returns>获取http连接对应图片的响应流</returns>
        public static MemoryStream GetResponseStream(string http)
        {
            var req = WebRequest.Create(http) as HttpWebRequest;

            var ms = new MemoryStream();

            using (WebResponse resp = req.GetResponse())
            {
                var stream = resp.GetResponseStream();
                stream.CopyTo(ms);
            }

            return ms;
        }

        /// <summary>
        /// 保存压缩后的图片到本地
        /// </summary>
        /// <param name="img">被压缩的图片</param>
        /// <param name="newFileName">压缩后产生的图片</param>
        public static void CompressImage(Image img, string newFileName)
        {
            Compress(img, newFileName, 680, 680, 65);
        }

        /// <summary>
        /// 返回压缩后的字节流
        /// </summary>
        /// <param name="img">被压缩的图片</param>
        /// <returns>返回压缩后的字节流</returns>
        public static byte[] CompressStream(Image img)
        {
            var ms = Compress(img, 680, 680, 65);

            return ms.ToArray();
        }

        /// <summary>
        /// 返回压缩后的流
        /// </summary>
        /// <param name="iSource">原图片</param>
        /// <param name="dHeight">高度</param>
        /// <param name="dWidth">宽度</param>
        /// <param name="quality">压缩质量 1-100</param>
        /// <returns>返回压缩后的流</returns>
        public static MemoryStream Compress(Image iSource, int dHeight, int dWidth, int quality)
        {
            EncoderParameters ep;
            ImageCodecInfo jpegICIinfo;
            Bitmap bitmap = Compress(iSource, dHeight, dWidth, quality, out ep, out jpegICIinfo);

            try
            {
                var stream = new MemoryStream();

                if (jpegICIinfo != null)
                {
                    bitmap.Save(stream, jpegICIinfo, ep);
                }
                else
                {
                    bitmap.Save(stream, iSource.RawFormat);
                }

                return stream;
            }
            catch
            {
                return null;
            }
            finally
            {
                iSource.Dispose();
                bitmap.Dispose();
            }

        }

        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="dHeight">高度</param>
        /// <param name="dWidth">宽度</param>
        /// <param name="quality">压缩质量 1-100</param>
        public static void Compress(Image iSource, string dFile, int dHeight, int dWidth, int quality)
        {
            EncoderParameters ep; ImageCodecInfo jpegICIinfo;
            Bitmap bitmap = Compress(iSource, dHeight, dWidth, quality, out ep, out jpegICIinfo);

            try
            {
                if (jpegICIinfo != null)
                {
                    bitmap.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    bitmap.Save(dFile, iSource.RawFormat);
                }
            }
            catch
            {

            }
            finally
            {
                iSource.Dispose();
                bitmap.Dispose();
            }
        }

        /// <summary>
        /// 返回指定大小的图像
        /// </summary>
        /// <param name="iSource">原图片</param>
        /// <param name="dHeight">高度</param>
        /// <param name="dWidth">高度</param>
        /// <param name="quality">压缩质量 1-100</param>
        /// <param name="ep">编码参数</param>
        /// <param name="jpegICIinfo">图像编码信息</param>
        /// <returns>返回指定大小的图像</returns>
        public static Bitmap Compress(Image iSource, int dHeight, int dWidth, int quality, out EncoderParameters ep, out ImageCodecInfo jpegICIinfo)
        {
            ImageFormat tFormat = iSource.RawFormat;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);

            if (tem_size.Width > dHeight || tem_size.Width > dWidth)
            {
                if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }
            Bitmap bitmap = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(bitmap);
            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            //以下代码为保存图片时，设置压缩质量
            ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = quality;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;

            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            jpegICIinfo = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICIinfo = arrayICI[x];
                    break;
                }
            }

            return bitmap;
        }

        #endregion

        #region 将BMP图形转换为JPEG

        private static Image GetBMPImage(string bmpFileName)
        {
            using (var stream = File.OpenRead(bmpFileName))
            {
                var bitMap = new Bitmap(stream);
                //Image image = bitMap;
                Image newImage = bitMap.GetThumbnailImage(bitMap.Width, bitMap.Height, null, new IntPtr());
                var graphics = Graphics.FromImage(newImage);
                graphics.DrawImage(newImage, 0, 0, newImage.Width, newImage.Height);
                graphics.Dispose();

                return newImage;
            }
        }

        public static MemoryStream ConvertBMPToJPEGMemoryStream(string bmpFileName)
        {
            var stream = new MemoryStream();

            var image = GetBMPImage(bmpFileName);
            image.Save(stream, ImageFormat.Jpeg);

            return stream;
        }

        #endregion
    }
}
